package com.gwtintegration.smartrf.client;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.web.bindery.requestfactory.shared.BaseProxy;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.smartgwt.client.data.Record;

public abstract class ProxyConverter<T extends BaseProxy> {

	public abstract Record toRecord(T proxy, ConverterCache converterCache);

	public abstract T toProxy(Record record, RequestContext requestContext, ConverterCache converterCache);

	public abstract boolean hasSameId(Record record, T proxy);

	@SuppressWarnings("unchecked")
	protected T getProxy(Record record) {
		if (record != null && record.getJsObj() != null) {
			return (T) __getProxy(record.getJsObj());
		}
		return null;
	}

	protected void setProxy(Record record, T proxy) {
		if (record != null && record.getJsObj() != null) {
			__setProxy(record.getJsObj(), proxy);
		}
	}

	private static native void __setProxy(JavaScriptObject object, Object proxy)
	/*-{
		// Workaround to solve a stack overflow on smartgwt clone method.
	 	object.__proxy = new Object() {
	 		__getProxy : function() { return proxy; }
	 	};
	}-*/;

	private static native Object __getProxy(JavaScriptObject object)
	/*-{
		if (object.__proxy) {
			return object.__proxy.__getProxy();
		}

		return null;
	}-*/;
}
